package com.zx.springcloud.controller;

import com.netflix.appinfo.InstanceInfo;

import com.zx.springcloud.entities.CommonResult;
import com.zx.springcloud.entities.Payment;
import com.zx.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@Slf4j
@RequestMapping("/payment")
public class PaymentController {

    @Resource
    private PaymentService paymentService;

    /**
     * 服务发现 获取服务信息
     */
    @Resource
    private DiscoveryClient discoveryClient;

    @Value("${server.port}")
    private String port;

    @PostMapping("/create")
    public CommonResult create(@RequestBody Payment payment) {
        int result = paymentService.create(payment);
        log.info("插入数据的ID:\t" + payment.getId());
        log.info("插入结果：" + result);
        int a = 10/5;
        if (result > 0) {
            return new CommonResult(200, "插入数据成功,port="+port, result);
        } else {
            return new CommonResult(444, "插入数据失败", null);
        }
    }

    @GetMapping(value = "/get/{id}")
    public CommonResult getPaymentById(@PathVariable Long id) {
        Payment payment = paymentService.getPaymentById(id);
        log.info("*** 查询结果123" + payment+"O(∩_∩)O哈哈~");
        if (payment != null) {
            return new CommonResult(200, "查询成功,port="+port, payment);
        } else {
            return new CommonResult(444, "没有对应记录，id为"+id, null);
        }
    }

    @GetMapping(value="/discovery")
    public Object discovery(){

        List<String> services = discoveryClient.getServices();

        for(String element : services){
            log.info("*****element:" + element);
        }

        List<ServiceInstance> instances =  discoveryClient.getInstances("cloud-payment-service");
        for(ServiceInstance instance : instances){
            log.info(instance.getServiceId()+"\t"+instance.getHost()+"\t"+instance.getPort()+"\t"+instance.getUri());
        }

        return instances;
    }

}
